use strict;
use warnings FATAL => 'all';

use Test::More tests => 25;
use File::Temp qw(tempdir);
use File::Slurp;
use File::Path qw(rmtree);
use Data::Dumper;

my $td = tempdir("/tmp/cgifs_tmp_XXXXXX"); # , CLEANUP => 1);
mkdir "$td/mnt";
mkdir "$td/scripts";
mkdir "$td/files";

my $res = `./cgifs $td/mnt 2>&1`;
like($res, qr/Usage:/) or exit 1;

`./cgifs $td/mnt $td/scripts $td/files`;
is($?, 0) or exit 1;

my $pscmd = "ps auxx | grep cgifs_tmp | grep -v grep | grep -v perl";
my @ps = `$pscmd`;
is(@ps, 1);

my ($pid) = ($ps[0] =~ /^\w+\s+(\d+)/);
my @of = `lsof -p $pid`;
is(@of, 14) or diag(Dumper(\@of));

write_file("$td/files/hello.txt", "hello\n");
isnt(-f "$td/mnt/hello.txt", undef);
is(read_file("$td/mnt/hello.txt"), "hello\n");

write_file("$td/scripts/a.sh", <<'ENDS');
#!/bin/sh
echo AAA > $1
ENDS
`chmod +x $td/scripts/a.sh`;

isnt(-f "$td/mnt/a.sh/aaa.txt", undef);
is(read_file("$td/mnt/a.sh/aaa.txt"), "AAA\n");

isnt(-f "$td/files/a.sh/aaa.txt", undef);
is(read_file("$td/files/a.sh/aaa.txt"), "AAA\n");

write_file("$td/files/a.sh/bbb.txt", "BBB\n");
is(read_file("$td/mnt/a.sh/bbb.txt"), "BBB\n");

my @of2 = `lsof -p $pid`;
is(@of2, @of) or diag(Dumper(\@of2));

unlink("$td/files/a.sh/bbb.txt");
is(read_file("$td/mnt/a.sh/bbb.txt"), "AAA\n");

write_file("$td/scripts/foo.sh", <<'ENDS');
#!/bin/sh
echo FOO > $1
ENDS

is(-f "$td/mnt/foo.sh/aaa.txt", undef);
like(`tail /var/log/syslog`, qr/foo\.sh/);

is(-f "$td/mnt/nosuchfile.sh/aaa.txt", undef);
like(`tail /var/log/syslog`, qr/nosuchfile\.sh/);

write_file("$td/scripts/bar.sh", <<'ENDS');
#!/bin/sh
echo BARERROR 1>&2
ENDS
`chmod +x $td/scripts/bar.sh`;

is(-f "$td/mnt/bar.sh/aaa.txt", undef);
like(`tail /var/log/syslog`, qr/bar.sh.*BARERROR/);

write_file("$td/scripts/sl.pl", <<'ENDS');
#!/usr/bin/perl -w
use strict;

exit if (fork);
close \*STDERR;
sleep 20;
ENDS
`chmod +x $td/scripts/sl.pl`;

is(-f "$td/mnt/sl.pl/aaa.txt", undef);

$res = `fusermount -u $td/mnt 2>&1`;
is($?, 0) or diag($res);

@ps = `$pscmd`;
is(@ps, 0);

`./cgifs $td/mnt $td/scripts $td/files`;
is($?, 0) or exit 1;

sleep 2;

$res = `fusermount -u $td/mnt 2>&1`;
is($?, 0) or diag($res);

@ps = `ps auxx | grep cgifs_tmp | grep -v grep | grep -v perl`;
if (@ps > 0) {
	sleep 1;
	@ps = `ps auxx | grep cgifs_tmp | grep -v grep | grep -v perl`;
}
is(@ps, 0);

rmtree($td);

